// 3. 实现一个批量请求函数 multiRequest(urls, maxNum)，要求如下：
// ● 要求最大并发数 maxNum 
// ● 每当有一个请求返回，就留下一个空位，可以增加新的请求 
// ● 所有请求完成后，结果按照 urls 里面的顺序一次打印
function request(url){
  let time = Math.random() * 1000
  return new Promise( (resovle,reject) => {
    setTimeout(() => {
      console.log('res' + url)
      resovle('res' + url)
    }, time)
  })
}

function multiRequest(urls, maxNum){
  let index = 0
  let currNum = 0
  let res = []
  let len = urls.length
  function req (){
    if(currNum >= maxNum) {
      console.log('超过最大并发数等待中..')
      return
    }
    currNum++
    index++
    request(urls.shift()).then(resp => {
      res[index] = resp
      console.log(resp)
      currNum--
    }, err => {
      res[index] = err
      currNum--
    })
  }
  while(index < len){
    req()
  }
  return res
}

const urls = ['www.baidu1.com', 'www.baidu2.com', 'www.baidu3.com', 'www.baidu4.com', 'www.baidu5.com',
  'www.baidu6.com', 'www.baidu7.com'
]
multiRequest(urls, 4).then((res) => console.log(res))

// 掘金参考
function multiRequestLimitNum (reqArr, limitNum) {
  const reqLen = reqArr.length
  const resArr = new Array(reqLen)
  let i = 0
  return new Promise(async (resolve, reject) => {
    const maxNum = reqLen >= limitNum ? limitNum : reqLen
    while (i < maxNum) {
      reqFn()
    }
    async function reqFn () {
      const cur = i++
      const fn = reqArr[cur]
      const data = await fn().catch((err) => { return err })
      resArr[cur] = data
      if (i === reqArr.length) resolve(resArr)
      else reqFn()
    }
  })
}